/*
** sv_udp_daytime.c -- servidor udp daytime
*/


#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define MAXLINE 200     /* tamanho maximo da mensagem */


/* daemon chamado pelo inetd */
void daemon_inetd(const char *pname) {
  openlog(pname, LOG_PID, 0);
}


/* daytime */
void daytime(char *buf) {
  char *ctime();
  time_t  time(), now;
  (void) time(&now);
  sprintf(buf, "%s", ctime(&now));
}


/* funcao principal */
int main(int argc, char * argv[]) {

  unsigned int sin_size;
  struct sockaddr_in their_addr;
  char buf[MAXLINE];


  /* inicializa log */
  daemon_inetd(argv[0]);


  /* acha o cliente */
  sin_size = sizeof(struct sockaddr_in);
  if (recvfrom(STDIN_FILENO, buf, MAXLINE, 0,
	       (struct sockaddr *)&their_addr, &sin_size) == -1) {
    syslog(LOG_ERR|LOG_USER, "== recvfrom: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }    


  /* envia o daytime */
  daytime(buf);
    
  if (sendto(STDOUT_FILENO, buf, sizeof(buf), 0,
	     (struct sockaddr *)&their_addr,
	     sizeof(struct sockaddr)) == -1) {
    syslog(LOG_ERR|LOG_USER, "== sendto: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }
   
  syslog(LOG_INFO|LOG_USER, ">> servico %s concluido (pid:%d) ; cliente: %s - porta: %d\n",
	 argv[0], getpid(),
	 inet_ntoa(their_addr.sin_addr), their_addr.sin_port);

  /* fecha fds */
  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  
  return EXIT_SUCCESS;
}

